package com.cloud.SpringMVC.controller.controller;

import com.alibaba.fastjson.JSON;
import com.cloud.SpringMVC.bean.User;
import com.cloud.SpringMVC.utils.JsonUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

@Controller
public class UserController {
    /**
     * Jackson测试
     *1.导包
     *2.增加配置解决jackson中文乱码问题
     * @return
     * @throws JsonProcessingException
     */
    @RequestMapping("/User")
    @ResponseBody
    public String getUser() throws JsonProcessingException {
        User user = new User();
        user.setAge(30);
        user.setName("舒传彪");
        user.setSex("man");

        ObjectMapper mapper = new ObjectMapper();
        String result = mapper.writeValueAsString(user);

        return result;
    }

    @RequestMapping("/UserJson")
    @ResponseBody
    public String getUserJson() throws JsonProcessingException {
        User user = new User();
        user.setAge(18);
        user.setName("Tony");
        user.setSex("man");

        String jsonStr = JsonUtils.getJson(user);
        return jsonStr;
    }

    @RequestMapping("/UserFastJson")
    @ResponseBody
    public String getUserFastJson(){
        List userList = new ArrayList<User>();
        for (int i = 0; i < 10; ++i) {
            User user = new User("Tony",23, "women");
            userList.add(user);
        }
        String userListStr = JSON.toJSONString(userList);
        return userListStr;
    }
}
